package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.db.FxRateDb;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.utils.UUIDUtil;
import com.dctp.common.cache.RoleCache;
import com.dctp.common.cache.UserCache;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.dctp.ems.config.OpsLog;
import com.dctp.ems.interceptor.OpsLogInterceptor;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
import com.jfinal.aop.Before;
import com.dctp.common.vo.QueryResult;

@Path("/roleRecharge")
public class RoleRechargeController extends BaseController {

    /**
     * GET /recharge/list
     * 分页查询充值记录，支持user_id、audit_status、create_time范围
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        QueryResult qr = buildRechargeQuery();
        String select = "SELECT * ";
        String from = "FROM dctp_role_recharge" + qr.where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, qr.params.toArray());
        List<Record> list = p.getList();
        for (Record r : list) {
            Long uid = r.getLong("user_id");
            if (uid != null) {
                Record user = UserCache.getShowInfo(uid);
                r.set("user", user != null ? user.getColumns() : null);
            }
            LocalDateTime createTime = r.getLocalDateTime("create_time");
            if (createTime != null) {
                r.set("create_time", DateUtil.format(createTime));
            }
            LocalDateTime auditTime = r.getLocalDateTime("audit_time");
            if (auditTime != null) {
                r.set("audit_time", DateUtil.format(auditTime));
            }

            Long roleId = r.getLong("role_id");
            r.set("role_name", RoleCache.getRoleName(roleId));
        }
        renderJson(JsonResult.successWithData(
            new PageResult<>(list, p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * POST /recharge/audit/:id
     * 审核充值记录
     * 参数：audit_status(1=通过,2=拒绝), remark(可选)
     */
    @Before({Tx.class, OpsLogInterceptor.class})
    @OpsLog(module = "角色管理",
            action = "申请审核",
            table = "dctp_role_recharge",
            fields = {"audit_status"})
    public void audit() {
        Long id = getParaToLong(0);
        Record params = jsonBody();
        Integer auditStatus = params.getInt("audit_status");
        String remark = params.get("remark", "");
        if (id == null || auditStatus == null) {
            throw new RuntimeException("参数缺失");
        }
        Long auditorId = getUserId();
        Record recharge = Db.findById("dctp_role_recharge", id);
        if (recharge == null) {
            throw new RuntimeException("记录不存在");
        }
        Integer rechargeAuditStatus = recharge.getInt("audit_status");
        if (rechargeAuditStatus == null || rechargeAuditStatus != 0) {
            throw new RuntimeException("该订单已审核，不能重复操作");
        }
        int r = Db.update("UPDATE dctp_role_recharge SET audit_status=?, auditor_id=?, audit_time=NOW(), remark=?, update_time=NOW() WHERE id=?",
                auditStatus, auditorId, remark, id);
        if (r == 0) {
            throw new RuntimeException("审核失败或记录不存在");
        }
        // 审核通过，升级用户
        if (auditStatus == 1) {
            Long userId = recharge.getLong("user_id");
            Long roleId = recharge.getLong("role_id");
            // 判断当前用户角色level
            Integer currentRoleId = Db.queryInt("SELECT role_id FROM dctp_user WHERE id = ?", userId);
            Integer currentLevel = Db.queryInt("SELECT level FROM dctp_role WHERE id = ?", currentRoleId);
            Integer upgradeLevel = Db.queryInt("SELECT level FROM dctp_role WHERE id = ?", roleId);
            if (currentLevel == null || upgradeLevel == null) {
                throw new RuntimeException("角色等级信息不存在");
            }
            if (currentLevel < upgradeLevel) {
                // 升级用户角色
                //设置有效期
                LocalDateTime now = LocalDateTime.now();
                int updateRole = Db.update("UPDATE dctp_user SET role_id = ?,dead_line = ? WHERE id = ?", roleId, now.plusYears(1), userId);
                if (updateRole != 1) {
                    throw new RuntimeException("用户角色升级失败");
                }

                String filed = getRoleField(roleId);
                if (StringUtil.isNotEmpty(filed)) {
                    String sql = "update dctp_user set " + filed + " = ? " +
                            "where parent_id = ? ";
                    Db.update(sql, userId, userId );
                }

                //删除缓存
                UserCache.delete(userId);
            }
        }
        setAttr("oldRecord", recharge);
        renderJson(JsonResult.success());
    }

    /**
     * GET /recharge/export
     * 导出充值记录Excel，支持user_id、audit_status、create_time范围
     */
    public void export() {
        QueryResult qr = buildRechargeQuery();
        String sql = "SELECT * FROM dctp_role_recharge" + qr.where + " ORDER BY id DESC";
        List<Record> list = Db.find(sql, qr.params.toArray());
        for (Record r : list) {
            Long uid = r.getLong("user_id");
            Record user = uid != null ? UserCache.getBasic(uid) : null;
            LocalDateTime createTime = r.getLocalDateTime("create_time");
            if (createTime != null) {
                r.set("create_time", DateUtil.format(createTime));
            }
            LocalDateTime auditTime = r.getLocalDateTime("audit_time");
            if (auditTime != null) {
                r.set("audit_time", DateUtil.format(auditTime));
            }
            r.set("_user_login_account", user != null ? user.getStr("login_account") : "");
        }
        // 创建Excel
        try (Workbook wb = new XSSFWorkbook()) {
            Sheet sheet = wb.createSheet("充值记录");
            int rowIdx = 0;
            Row head = sheet.createRow(rowIdx++);
            String[] fields = {"id", "user_id", "_user_login_account", "amount", "chain_type", "deposit_address", "tx_hash", "audit_status", "auditor_id", "audit_time", "remark", "create_time"};
            String[] titles = {"ID", "用户ID", "用户账号", "金额(USDT)", "链类型", "收款地址", "TxHash", "审核状态", "审核人", "审核时间", "备注", "创建时间"};
            for (int i = 0; i < titles.length; i++) head.createCell(i).setCellValue(titles[i]);
            for (Record r : list) {
                Row row = sheet.createRow(rowIdx++);
                for (int i = 0; i < fields.length; i++) {
                    Object val = r.get(fields[i]);
                    row.createCell(i).setCellValue(val != null ? val.toString() : "");
                }
            }
            String dateStr = DateUtil.format(DateUtil.now(), "yyyyMMdd");
            String randomStr = UUIDUtil.orderedUUID().substring(0, 8);
            String fileName = "充值记录-" + dateStr + "-" + randomStr + ".xlsx";
            HttpServletResponse resp = getResponse();
            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            wb.write(resp.getOutputStream());
            renderNull();
        } catch (Exception e) {
            throw new RuntimeException("导出失败", e);
        }
    }

    /**
     * 封装充值记录查询参数，返回 where/params
     */
    private QueryResult buildRechargeQuery() {
        Long userId = getParaToLong("user_id");
        Integer auditStatus = getParaToInt("audit_status", null);
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (auditStatus != null) {
            where.append(" AND audit_status = ?");
            params.add(auditStatus);
        }
        if (startTime != null && !startTime.isEmpty()) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (endTime != null && !endTime.isEmpty()) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }
        String filterField = getFilterField();
        Long filterUserId = getRequestUser().getLong("user_id");
        if (filterField != null && filterUserId != null) {
            where.append(" AND ").append(filterField).append(" = ?");
            params.add(filterUserId);
        }

        String roleKey = getPara("roleKey");
        Long roleUserId = getParaToLong("roleUserId");
        if (StringUtil.isNotEmpty(roleKey) && null != roleUserId) {
            where.append(" AND ").append(roleKey).append(" = ?");
            params.add(roleUserId);
        }

        return new QueryResult(where, params);
    }
}
